#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/6/10 8:22
# @Author : linjinting
# @Project : custom_protocol
# @File : writeconfig.py
# @Software: PyCharm


import configparser
import os


class WriteConfig(object):
    """定义一个写入配置文件的类"""

    def __init__(self, config, filepath=None):
        if config is None:
            return
        self.m_config_dict = dict()
        if filepath:
            self.m_path = filepath
        else:
            root_dir = os.path.abspath('.')
            self.m_path = os.path.join(root_dir, "config\config.ini")
        if not os.path.exists(os.path.dirname(self.m_path)):
            os.mkdir(os.path.dirname(self.m_path))
        self.m_config = configparser.ConfigParser()
        self.m_config.read(self.m_path)

        self._dict_to_config(config)

    def _dict_to_config(self, config):
        for section, options in config.items():
            for k, v in options.items():
                if not self.m_config.has_section(section):
                    self.m_config.add_section(section)
                self.m_config.set(section, k, v)

    def write(self):
        with open(self.m_path, 'w') as fp:
            self.m_config.write(fp)


if __name__ == '__main__':
    root_dir = os.path.abspath('.')
    m_path = os.path.join(root_dir, "test\config.ini")
    print(os.path.dirname(m_path))
